<template>
  <a-modal
    title="高级查询构造器"
    :width="1000"
    :visible.sync="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    @cancel="handleCancel"
  >
    <a-row style="margin-bottom: 12px;">
      <a-col :md="12" :xs="24">
        <a-form layout="inline">
          <a-form-item label="过滤条件">
            <a-select
              style="min-width: 240px"
              placeholder="请选择过滤条件"
              v-model="queryType"
              :getPopupContainer="node=>node.parentNode"
            >
              <a-select-option value="and">AND（所有条件都要求匹配）</a-select-option>
              <a-select-option value="or">OR（条件中的任意一个匹配）</a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </a-col>
    </a-row>

    <a-form layout="inline">
      <a-row
        type="flex"
        style="margin-bottom:10px"
        :gutter="16"
        v-for="(item, index) in queryParams"
        :key="index"
      >
        <a-col :md="8" :xs="24" style="margin-bottom: 12px;">
          <a-select
            showSearch
            :filterOption="filterOption"
            placeholder="选择查询字段"
            style="width: 100%;"
            v-model="item.field"
            :getPopupContainer="node=>node.parentNode"
            @select="(val,option)=>handleSelected(option,item)"
          >
            <a-select-option
              :key="index"
              :value="it.value"
              v-for="(it,index) in fieldList"
            >{{ it.label }}</a-select-option>
          </a-select>
        </a-col>

        <a-col :md="4" :xs="24" style="margin-bottom: 12px;">
          <a-select
            placeholder="匹配规则"
            style="width: 100%"
            :value="item.rule"
            :getPopupContainer="node=>node.parentNode"
            @change="handleRuleChange(item, $event)"
          >
            <a-select-option value="eq">等于</a-select-option>
            <a-select-option value="like">包含</a-select-option>
            <a-select-option value="right_like">以..开始</a-select-option>
            <a-select-option value="left_like">以..结尾</a-select-option>
            <a-select-option value="in">在...中</a-select-option>
            <a-select-option value="ne">不等于</a-select-option>
            <a-select-option value="gt">大于</a-select-option>
            <a-select-option value="ge">大于等于</a-select-option>
            <a-select-option value="lt">小于</a-select-option>
            <a-select-option value="le">小于等于</a-select-option>
          </a-select>
        </a-col>
        <a-col :md="8" :xs="24" style="margin-bottom: 12px;">
          <!--判断各种输入框-->
          <a-input
            v-if="item.rowType === 'input'"
            v-model="item.val"
            style="width: 100%"
            :placeholder="'请输入' + item.rowName"
          ></a-input>
          <a-input-number
            v-else-if="item.rowType === 'input-number'"
            v-model="item.val"
            style="width: 100%"
            :placeholder="'请输入' + item.rowName"
          ></a-input-number>
          <a-select
            v-else-if="item.rowType === 'select'"
            v-model="item.val"
            style="width: 100%"
            :placeholder="'请选择' + item.rowName"
          >
            <a-select-option :key="it.value" v-for="it in item.options">{{ it.label }}</a-select-option>
          </a-select>
          <a-select
            v-else-if="item.rowType === 'select-multiple'"
            v-model="item.val"
            mode="multiple"
            style="width: 100%"
            :placeholder="'请选择' + item.rowName"
          >
            <a-select-option :key="it.value" v-for="it in item.options">{{ it.label }}</a-select-option>
          </a-select>
          <a-date-picker
            :showTime="{ defaultValue: item.defaultTime }"
            v-else-if="item.rowType === 'date'"
            :placeholder="'请选择' + item.rowName"
            style="width: 100%"
            format="YYYY-MM-DD HH:mm:ss"
            v-model="item.val"
          ></a-date-picker>
          <a-input v-else>

          </a-input>
        </a-col>
        <a-col :md="4" :xs="0" style="margin-bottom: 12px;">
          <a-button @click="handleAdd" icon="plus"></a-button>&nbsp;
          <a-button v-show="fieldSize" @click="handleDel( index )" icon="minus"></a-button>
        </a-col>
      </a-row>
    </a-form>
    <template slot="footer">
      <a-button :loading="confirmLoading" @click="handleCancel">关闭</a-button>
      <a-button :loading="confirmLoading" type="primary" @click="handleOk">查询</a-button>
    </template>
  </a-modal>
</template>

<script>
import moment from 'moment'
import { axios } from '@/utils/request'
export default {
  props: {
    showModel: {
      type: Boolean,
      default: false
    },
    fieldList: {
      type: Array,
      required: true
    }
  },
  name: 'BSuperQuery',
  data () {
    return {
      moment,
      visible: this.showModel,
      confirmLoading: false,
      queryType: 'and',
      queryParams: [
        {
          field: undefined,
          rule: 'eq'
        }
      ]
    }
  },
  watch: {
    showModel (newVal) {
      this.visible = newVal
    }
  },
  computed: {
    fieldSize () {
      return this.queryParams.length > 1
    }
  },
  methods: {
    handleOk () {
      if (!this.queryType) {
        this.$message.error('请选择过滤条件')
        return
      }
      if (!this.isNullArray(this.queryParams)) {
        const params = this.removeEmptyQueryParam(this.queryParams)

        for (const param of params) {
          console.log('======')
          moment.locale('zh-cn')

          if (Array.isArray(param.val)) {
            param.val = param.val.join(',')
          } else if (param.rowType === 'date') {
            param.val = moment(param.val).format('YYYY-MM-DD HH:mm:ss')
          }
        }
        this.$emit('ok', this.queryType, params)
      } else {
        this.$message.error('不能查询空条件')
      }
    },
    handleCancel () {
      this.visible = false
      this.$emit('ok')
    },
    // 处理选择的查询字段
    handleSelected (node, item) {
      const it = this.fieldList.find(it => it.value === item.field)
      item['rowType'] = it.type
      item['rowName'] = it.label
      if (it.options) {
        item['options'] = it.options
      }
      if (it.dicUrl) {
        axios({
          url: it.dicUrl,
          method: 'GET'
        }).then(res => {
          item['options'] = res.data
        })
      }
      this.$set(item, 'val', undefined)
    },
    // 查询字段搜索
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 搜索类型
    handleRuleChange (item, newValue) {
      this.$set(item, 'rule', newValue)
    },
    // 添加搜索条件
    handleAdd () {
      this.queryParams.push({ rule: 'eq' })
    },
    // 删除搜索条件
    handleDel (index) {
      this.queryParams.splice(index, 1)
    },
    // 工具类 判断是不是空数组对象
    isNullArray (array) {
      if (!array || array.length === 0) {
        return true
      }
      if (array.length === 1) {
        const obj = array[0]
        if (!obj.field || (obj.val == null || obj.val === '') || !obj.rule) {
          return true
        }
      }
      return false
    },
    removeEmptyQueryParam (arr) {
      const array = JSON.parse(JSON.stringify(arr))
      for (let i = 0; i < array.length; i++) {
        const item = array[i]
        if (item == null || Object.keys(item).length <= 0 || !item.field) {
          array.splice(i--, 1)
        } else {
          delete item.rowName
          if (Array.isArray(item.options)) {
            delete item.options
          }
        }
      }
      return array
    }
  }
}
</script>

<style scoped>
</style>
